//
//  ST_EngagementCentServer.swift
//  btvideo
//
//  Created by mac on 2021/2/22.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import RealmSwift


extension ST_EngagementCentServer{
    
    func startListening(){
//        重置 上传中 状态为 默认待上传
        let list = realm.objects(ST_EngagementCentLog.self).filter("state == 1")
        
        try! realm.write({
            list.forEach({$0.state = 0})
        })
        
        push_log()
    }
}

class ST_EngagementCentServer: NSObject {

    static let shared = ST_EngagementCentServer()
  
    private let realm = try! Realm()
    // Can't init is singleton
    private override init() {
        super.init()
    }
    
    func push_log()  {
        
        
        /// 小窗模式先不上报
        if ST_TIANEngagementManager.defaultManager.isSuspended {
            return
        }
        
        guard let id = ST_BTUserInfoManager.shared.current_account_info?.accid else{
            return
        }
        
        let readyList = realm.objects(ST_EngagementCentLog.self).filter("state == 0 && myId == %@",id)
        
        let failureList = realm.objects(ST_EngagementCentLog.self).filter("state == 3 && myId == %@",id)
        
        readyList.forEach { (item) in
            upload(log: item)
        }
        
        failureList.forEach { (item) in
            upload(log: item)
        }
    }
    
    
    fileprivate func upload(log:ST_EngagementCentLog){
        
        if log.startDate.secondsSince(log.endDate).abs < 1{
            return
        }
        
//        上传中
        try! realm.write({
            log.state = 1
        })
        
        
        let parameters = ["target_accid":log.herId,"start_int":log.startDate.unixTimestamp.int,"end_int":log.endDate.unixTimestamp.int,"sped_id":log.sped_id] as [String : Any]
        
        let logStr = "------------------\n url=\(PH.subCoinApi) parameters=\(parameters)"
        
        print(logStr, to: &engagementLogger)
        
        JVrequest(PH.subCoinApi,parameters:parameters) { (json) in
//            上传成功
           try! self.realm.write({
               log.state = 2
           })
            
            
            let resultStr = "------------------\n 返回正确 我传递的parameters=\(parameters)    返回json:" + (json.rawString() ?? "")
            
            print(resultStr, to: &engagementLogger)
            
            
            main_thread_execute {
                
                let userManager = ST_BTUserInfoManager.shared
                
                let realm = try! Realm()
               
                try! realm.write {
                    userManager.current_account_info?.userinfo?.localConsumeSweetCoin = 0
                }
                
                userManager.modify_sweet_coin(value: json["data"]["sweet_currency"].floatValue)
                
                userManager.modify_sweet_income(value: json["data"]["income"].doubleValue, outValue: json["data"]["income_out"].doubleValue)
                
                userManager.update_additional_impression_data(json: json["data"])
            }
            
            
            
            
            
        } failure: { (code, err) in
//            上传失败
            try! self.realm.write({
                log.state = 3
            })
            
            
            let resultStr = "------------------\n 返回失败 我传递的parameters=\(parameters)    返回json:" + err
            
            print(resultStr, to: &engagementLogger)
            
        }

        
        
    }
    
}
class ST_EngagementCentLog: Object {
    
    @objc dynamic var myId = ""
    
    @objc dynamic var herId = ""
    /**
     后台新增
     */
    @objc dynamic var sped_id = ""
    
    
    @objc dynamic var startDate = Date()
    
    @objc dynamic var endDate = Date()
    
//    0:默认待上传 1:上传中 2:上传成功 3:失败
    @objc dynamic var state = 0
}





var engagementLogger = ST_RegisterLog()


struct ST_RegisterLog: TextOutputStream {

    func write(_ string: String) {
        
        #if DEBUG
        let fm = FileManager.default
        let log = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("bitianRegistLog.txt")
        if let handle = try? FileHandle(forWritingTo: log) {
            handle.seekToEndOfFile()
            handle.write(string.data(using: .utf8)!)
            handle.closeFile()
        } else {
            try? string.data(using: .utf8)?.write(to: log)
        }
        #endif
        
    }
}
